<?php
/**
 * Skyline :: Foundational pattern framework
 * Copyright 2010-2011 Ian Unruh
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Skyline\Comparator;
use Skyline\Reflection\Property\AccessorInterface;
use Skyline\Reflection\Property\MethodAccessor;

/**
 * 
 * 
 * @author Ian Unruh <ianunruh@gmail.com>
 * @since Class avaliable since release 1.0
 */
class PropertyComparator extends DecoratedComparator
{
	/**
	 * @var AccessorInterface
	 */
	protected $accessor;
	
	/**
	 * @var string
	 */
	protected $propertyName;
	
	/**
	 * Class constructor
	 * 
	 * @param string $propertyName
	 * @param ComparatorInterface $comparator
	 * @param AccessorInterface $accessor [optional]
	 * @return void
	 */
	public function __construct($propertyName, ComparatorInterface $comparator, AccessorInterface $accessor = null)
	{
		parent::__construct($comparator);
		
		$this->accessor = ($accessor ?: $this->createDefaultAccessor());
		$this->propertyName = $propertyName;
	}
	
	/**
	 * Returns an integer comparison of the left value compared to the
	 * right value
	 * 
	 * @throws InvalidArgumentException If values cannot be compared because
	 *   they are incompatible with each other
	 * @throws InvalidArgumentException If values cannot be compared because
	 *   this comparator does not support them
	 * @param mixed $left
	 * @param mixed $right
	 * @return int
	 */
	public function compare($left, $right)
	{
		$lv = $this->accessor->getValue($left, $this->propertyName);
		$rv = $this->accessor->getValue($right, $this->propertyName);
		
		return $this->comparator->compare($lv, $rv);
	}
	
	/**
	 * Returns the name of the property being compared
	 * @return string
	 */
	public function getPropertyName()
	{
		return $this->propertyName;
	}
	
	/**
	 * Creates and returns a default property accessor if one is not provided
	 * in the constructor
	 * @return AccessorInterface
	 */
	protected function createDefaultAccessor()
	{
		return new MethodAccessor();
	}
}